package network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private final DatagramSocket socket;

    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);//指定端口号
    }

    public void start() throws IOException {
        System.out.println("服务器，启动！");
        while (true) {
            //接收请求
            System.out.println("接收请求");
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            //解析请求
            System.out.println("解析请求");
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //计算响应
            System.out.println("计算响应");
            String response = process(request);
            //发送响应
            System.out.println("发送响应");
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    0, response.getBytes().length,
                    requestPacket.getSocketAddress());//response.getBytes().length：中文字节数和字符数会有所差异
            socket.send(responsePacket);
            //打印日志
            System.out.println("打印日志");
            System.out.printf("[%s:%d] req=%s, resp=%s\n", responsePacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
        }
    }

    protected String process(String request) {
        return "echo:" + request;//无业务逻辑，回显即可
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer sever = new UdpEchoServer(9091);
        sever.start();
    }
}
